<template>
  <div class="test-mind-container">
    <div class="test-header">
      <h1>思维导图组件测试</h1>
      <div class="test-controls">
        <button class="btn btn-primary" @click="switchDataSet">
          切换数据集{{ currentDataSetIndex }}
        </button>
        <button class="btn btn-secondary" @click="toggleControls">
          {{ showControls ? "隐藏控制器" : "显示控制器" }}
        </button>
        <button class="btn btn-info" @click="toggleHeader">
          {{ showHeader ? "隐藏头部" : "显示头部" }}
        </button>
        <button
          :class="['btn', isEdit ? 'btn-success' : 'btn-warning']"
          @click="toggleEditMode"
        >
          {{ isEdit ? "🔧 编辑模式" : "👁️ 查看模式" }}
        </button>
      </div>
      <div class="test-controls-row">
        <!-- 高亮测试按钮 -->
        <div class="control-group">
          <label class="control-label">高亮测试</label>
          <button class="btn btn-primary" @click="testHighlight">
            测试高亮
          </button>
          <button class="btn btn-secondary" @click="clearHighlight">
            清除高亮
          </button>
          <select
            class="type-selector"
            @change="highlightNodeByType($event.target.value)"
          >
            <option value="">按类型高亮</option>
            <option value="核心领域">核心领域</option>
            <option value="数学基础">数学基础</option>
            <option value="编程语言">编程语言</option>
            <option value="具体技术/概念">具体技术/概念</option>
            <option value="应用领域">应用领域</option>
          </select>
          <select
            class="level-selector"
            @change="showByLevel($event.target.value)"
          >
            <option value="">按层级展示</option>
            <option value="1">第1层</option>
            <option value="2">第2层</option>
            <option value="3">第3层</option>
            <option value="all">全部展开</option>
          </select>
        </div>

        <!-- 节点管理测试按钮 -->
        <div class="control-group">
          <label class="control-label">节点管理</label>
          <button class="btn btn-success" @click="testAddNode">添加节点</button>
          <button class="btn btn-warning" @click="testEditNode">
            编辑节点
          </button>
          <button class="btn btn-danger" @click="testRemoveNode">
            删除节点
          </button>
          <button class="btn btn-info" @click="testBatchAdd">批量添加</button>
          <button class="btn btn-purple" @click="testBatchRemove">
            批量删除
          </button>
          <button class="btn btn-gray" @click="getCurrentData">获取数据</button>
        </div>
      </div>
    </div>
    <div class="test-mind">
      <!-- 思维导图组件 -->
      <Mind
        ref="mindMapRef"
        :mindMapData="currentDataSet"
        :themeConfig="themeConfig"
        :isEdit="isEdit"
        @node-context-menu-action="handleContextMenuAction"
      >
      </Mind>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import Mind from "./Mind.vue";

// 测试数据
const showControls = ref(true);
const showHeader = ref(true);
const currentDataSetIndex = ref(0);
const isEdit = ref(true);
const mindMapRef = ref(null);

// 多个数据集用于测试
const dataSets = [
  {
    title: "计算机科学知识图谱",
    data: {
      nodes: [
        { id: "cs_foundation", label: "计算机科学基础", type: "核心领域" },
        { id: "data_structures", label: "数据结构", type: "核心领域" },
        { id: "algorithms", label: "算法", type: "核心领域" },
        { id: "os", label: "操作系统", type: "核心领域" },

        { id: "computer_networks", label: "计算机网络", type: "核心领域" },
        { id: "tcp_ip", label: "TCP/IP协议", type: "具体技术/概念" },

        {
          id: "sorting_searching",
          label: "排序/查找算法",
          type: "具体技术/概念",
        },
        { id: "ai", label: "人工智能", type: "应用领域" },
      ],
      links: [
        { source: "cs_foundation", target: "data_structures", label: "包含" },
        { source: "cs_foundation", target: "algorithms", label: "包含" },
        { source: "cs_foundation", target: "os", label: "包含" },
        {
          source: "discrete_math",
          target: "data_structures",
          label: "是...的基础",
        },
        { source: "discrete_math", target: "algorithms", label: "是...的基础" },
        { source: "data_structures", target: "array_list", label: "包含" },
        { source: "data_structures", target: "tree_graph", label: "包含" },
        { source: "algorithms", target: "sorting_searching", label: "包含" },
        { source: "algorithms", target: "ai", label: "应用于" },
        { source: "os", target: "computer_networks", label: "是...的基础" },
        { source: "computer_networks", target: "tcp_ip", label: "包含" },
        { source: "databases", target: "sql", label: "使用" },
        { source: "databases", target: "web_dev", label: "应用于" },
        { source: "python", target: "data_structures", label: "用于实现" },
        { source: "python", target: "ai", label: "用于实现" },
        { source: "python", target: "web_dev", label: "用于实现" },
        { source: "c_plus_plus", target: "os", label: "用于实现" },
        { source: "java", target: "oop", label: "是...的范例" },
        { source: "java", target: "web_dev", label: "用于实现" },
        { source: "oop", target: "software_engineering", label: "是...的基础" },
      ],
    },
  },
  {
    title: "前端技术栈",
    data: {
      nodes: [
        { id: "frontend", label: "前端开发", type: "核心领域" },
        { id: "html", label: "HTML", type: "基础技术" },
        { id: "css", label: "CSS", type: "基础技术" },
        { id: "javascript", label: "JavaScript", type: "基础技术" },
        { id: "vue", label: "Vue.js", type: "框架" },
        { id: "react", label: "React", type: "框架" },
        { id: "typescript", label: "TypeScript", type: "进阶技术" },
        { id: "webpack", label: "Webpack", type: "工具" },
        { id: "vite", label: "Vite", type: "工具" },
      ],
      links: [
        { source: "frontend", target: "html", label: "基于" },
        { source: "frontend", target: "css", label: "基于" },
        { source: "frontend", target: "javascript", label: "基于" },
        { source: "javascript", target: "vue", label: "构建" },
        { source: "javascript", target: "react", label: "构建" },
        { source: "javascript", target: "typescript", label: "扩展为" },
        { source: "vue", target: "vite", label: "使用" },
        { source: "react", target: "webpack", label: "使用" },
      ],
    },
  },
];

// 当前数据集
const currentDataSet = computed(() => {
  const data = dataSets[currentDataSetIndex.value].data;
  console.log("当前数据集:", data);
  return data;
});
const currentTitle = computed(() => {
  const title = dataSets[currentDataSetIndex.value].title;
  return title;
});

// 自定义主题配置
const themeConfig = ref({
  root: {
    fillColor: "#e53e3e",
    borderColor: "#e53e3e",
  },
  second: {
    fillColor: "#38a169",
    borderColor: "#38a169",
  },
  node: {
    fillColor: "#3182ce",
    borderColor: "#3182ce",
  },
});

// 测试方法
const switchDataSet = () => {
  currentDataSetIndex.value = (currentDataSetIndex.value + 1) % dataSets.length;
};

const toggleControls = () => {
  showControls.value = !showControls.value;
};

const toggleHeader = () => {
  showHeader.value = !showHeader.value;
};

// 控制功能方法
const testHighlight = () => {
  if (mindMapRef.value) {
    const a = ["数据结构", "HTML"][currentDataSetIndex.value];
    mindMapRef.value.highlightNodeAndChildrenByNodeName(a);
  }
};

const clearHighlight = () => {
  if (mindMapRef.value) {
    mindMapRef.value.clearHighlight();
  }
};

const highlightNodeByType = (type) => {
  if (type && mindMapRef.value) {
    mindMapRef.value.highlightNodeByType(type);
  }
};

const showByLevel = (level) => {
  if (level && mindMapRef.value) {
    mindMapRef.value.showByLevel(level);
  }
};

// 节点管理测试方法
let nodeCounter = 1; // 用于生成唯一的节点ID

// 测试添加节点
const testAddNode = () => {
  if (!mindMapRef.value) {
    console.error("思维导图实例不可用");
    return;
  }

  const newNodeId = `test_node_${nodeCounter++}`;
  const nodeData = {
    id: newNodeId,
    label: `测试节点${nodeCounter - 1}`,
    type: "测试类型",
    description: "这是一个测试节点",
  };

  // 随机选择一个父节点
  const currentData = mindMapRef.value.getCurrentData();
  if (currentData && currentData.nodes.length > 0) {
    const randomParentIndex = Math.floor(
      Math.random() * currentData.nodes.length
    );
    const parentNodeId = currentData.nodes[randomParentIndex].id;

    const linkData = {
      label: "测试关系",
    };

    const success = mindMapRef.value.addNode(nodeData, parentNodeId, linkData);
    if (success) {
      console.log(`✅ 成功添加节点: ${newNodeId}`);
      alert(`✅ 成功添加节点: ${nodeData.label}`);
    } else {
      console.error(`❌ 添加节点失败: ${newNodeId}`);
      alert(`❌ 添加节点失败`);
    }
  } else {
    // 如果没有现有节点，作为根节点添加
    const success = mindMapRef.value.addNode(nodeData);
    if (success) {
      console.log(`✅ 成功添加根节点: ${newNodeId}`);
      alert(`✅ 成功添加根节点: ${nodeData.label}`);
    } else {
      console.error(`❌ 添加根节点失败: ${newNodeId}`);
      alert(`❌ 添加根节点失败`);
    }
  }
};

// 测试编辑节点
const testEditNode = () => {
  if (!mindMapRef.value) {
    console.error("思维导图实例不可用");
    return;
  }

  const currentData = mindMapRef.value.getCurrentData();
  if (!currentData || currentData.nodes.length === 0) {
    alert("❌ 没有可编辑的节点");
    return;
  }

  // 随机选择一个节点进行编辑
  const randomIndex = Math.floor(Math.random() * currentData.nodes.length);
  const targetNode = currentData.nodes[randomIndex];

  const updateData = {
    label: `${targetNode.label} (已编辑)`,
    type: "已编辑类型",
    lastModified: new Date().toISOString(),
  };

  const success = mindMapRef.value.editNode(targetNode.id, updateData);
  if (success) {
    console.log(`✅ 成功编辑节点: ${targetNode.id}`);
    alert(`✅ 成功编辑节点: ${updateData.label}`);
  } else {
    console.error(`❌ 编辑节点失败: ${targetNode.id}`);
    alert(`❌ 编辑节点失败`);
  }
};

// 测试删除节点
const testRemoveNode = () => {
  if (!mindMapRef.value) {
    console.error("思维导图实例不可用");
    return;
  }

  const currentData = mindMapRef.value.getCurrentData();
  if (!currentData || currentData.nodes.length === 0) {
    alert("❌ 没有可删除的节点");
    return;
  }

  // 找到测试节点或随机选择一个节点删除
  let targetNode = currentData.nodes.find((node) =>
    node.id.startsWith("test_node_")
  );

  if (!targetNode) {
    // 如果没有测试节点，随机选择一个非根节点
    const nonRootNodes = currentData.nodes.filter(
      (node) => node.id !== "cs_foundation"
    );

    if (nonRootNodes.length === 0) {
      alert("❌ 没有可安全删除的节点");
      return;
    }

    const randomIndex = Math.floor(Math.random() * nonRootNodes.length);
    targetNode = nonRootNodes[randomIndex];
  }

  const removeChildren = Math.random() > 0.5; // 随机决定是否删除子节点

  const success = mindMapRef.value.removeNode(targetNode.id, false);
  if (success) {
    console.log(
      `✅ 成功删除节点: ${targetNode.id} (包含子节点: ${removeChildren})`
    );
    alert(
      `✅ 成功删除节点: ${targetNode.label} ${
        removeChildren ? "(包含子节点)" : ""
      }`
    );
  } else {
    console.error(`❌ 删除节点失败: ${targetNode.id}`);
    alert(`❌ 删除节点失败`);
  }
};

// 测试批量添加节点
const testBatchAdd = () => {
  if (!mindMapRef.value) {
    console.error("思维导图实例不可用");
    return;
  }

  const currentData = mindMapRef.value.getCurrentData();
  if (!currentData || currentData.nodes.length === 0) {
    alert("❌ 没有可用的父节点");
    return;
  }

  // 随机选择一个父节点
  const randomParentIndex = Math.floor(
    Math.random() * currentData.nodes.length
  );
  const parentNodeId = currentData.nodes[randomParentIndex].id;

  const batchNodes = [
    {
      nodeData: {
        id: `batch_node_${nodeCounter++}`,
        label: `批量节点A${nodeCounter - 1}`,
        type: "批量类型",
        batch: true,
      },
      parentNodeId: parentNodeId,
      linkData: { label: "批量关系A" },
    },
    {
      nodeData: {
        id: `batch_node_${nodeCounter++}`,
        label: `批量节点B${nodeCounter - 1}`,
        type: "批量类型",
        batch: true,
      },
      parentNodeId: parentNodeId,
      linkData: { label: "批量关系B" },
    },
    {
      nodeData: {
        id: `batch_node_${nodeCounter++}`,
        label: `批量节点C${nodeCounter - 1}`,
        type: "批量类型",
        batch: true,
      },
      parentNodeId: parentNodeId,
      linkData: { label: "批量关系C" },
    },
  ];

  const success = mindMapRef.value.addNodes(batchNodes);
  if (success) {
    console.log(`✅ 成功批量添加 ${batchNodes.length} 个节点`);
    alert(`✅ 成功批量添加 ${batchNodes.length} 个节点`);
  } else {
    console.error(`❌ 批量添加节点失败`);
    alert(`❌ 批量添加节点失败`);
  }
};

// 测试批量删除节点
const testBatchRemove = () => {
  if (!mindMapRef.value) {
    console.error("思维导图实例不可用");
    return;
  }

  const currentData = mindMapRef.value.getCurrentData();
  if (!currentData || currentData.nodes.length === 0) {
    alert("❌ 没有可删除的节点");
    return;
  }

  // 找到所有批量添加的测试节点
  const batchNodes = currentData.nodes.filter(
    (node) =>
      node.id.startsWith("batch_node_") || node.id.startsWith("test_node_")
  );

  if (batchNodes.length === 0) {
    alert("❌ 没有可批量删除的测试节点");
    return;
  }

  const nodeIds = batchNodes.map((node) => node.id);
  const removeChildren = false; // 批量删除时不删除子节点，避免意外

  const success = mindMapRef.value.removeNode(nodeIds, removeChildren);
  if (success) {
    console.log(`✅ 成功批量删除 ${nodeIds.length} 个节点`);
    alert(`✅ 成功批量删除 ${nodeIds.length} 个测试节点`);
  } else {
    console.error(`❌ 批量删除节点失败`);
    alert(`❌ 批量删除节点失败`);
  }
};

// 获取当前数据
const getCurrentData = () => {
  if (!mindMapRef.value) {
    console.error("思维导图实例不可用");
    return;
  }

  const currentData = mindMapRef.value.getCurrentData();
  console.log("📊 当前思维导图数据:", currentData);

  if (currentData) {
    alert(
      `📊 当前数据统计:\n节点数量: ${currentData.nodes.length}\n连接数量: ${currentData.links.length}\n详细信息请查看控制台`
    );
  } else {
    alert("❌ 无法获取当前数据");
  }
};

// 右键菜单事件处理函数
const handleContextMenuAction = (eventData) => {
  console.log("🎯 收到右键菜单操作事件:", eventData);

  const { action, nodeId, nodeText, timestamp, error, warning } = eventData;

  // 根据不同的操作类型显示不同的消息
  let message = "";
  let emoji = "";

  switch (action) {
    case "insertSiblingNode":
      emoji = "⊞";
      message = `${emoji} 插入同级节点`;
      break;
    case "insertChildNode":
      emoji = "└";
      message = `${emoji} 插入子级节点`;
      break;
    case "insertParentNode":
      emoji = "┌";
      message = `${emoji} 插入父级节点`;
      break;
    case "deleteNodeWithChildren":
      emoji = "🗑";
      message = `${emoji} 删除节点(含子节点)`;
      break;
    case "deleteCurrentNodeOnly":
      emoji = "✂";
      message = `${emoji} 仅删除当前节点`;
      break;
    default:
      emoji = "❓";
      message = `${emoji} 未知操作: ${action}`;
  }

  // 构建详细信息
  let details = `操作: ${message}`;
  if (nodeId) details += `\n节点ID: ${nodeId}`;
  if (nodeText) details += `\n节点文本: ${nodeText}`;
  if (timestamp) details += `\n时间: ${new Date(timestamp).toLocaleString()}`;
  if (error) details += `\n❌ 错误: ${error}`;
  if (warning) details += `\n⚠️ 警告: ${warning}`;

  // 在控制台输出详细信息
  console.log(`${message} - 详细信息:`, details);

  // 也可以选择是否显示弹窗（可以根据需要开启或关闭）
  // alert(details);
};
</script>

<style scoped lang="scss">
.test-mind-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f8fafc;
  overflow: hidden;
}

.test-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: white;
  border-bottom: 1px solid #e2e8f0;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

  h1 {
    margin: 0;
    font-size: 24px;
    font-weight: 700;
    color: #2d3748;
  }
}

.test-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

.test-controls-row {
  display: flex;
  flex-direction: column;
  gap: 16px;
  align-items: flex-start;
}

.control-group {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: wrap;
}

.control-label {
  font-weight: 600;
  color: #2d3748;
  font-size: 14px;
  min-width: 80px;
}

.btn {
  padding: 10px 16px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;

  &.btn-primary {
    background: #4299e1;
    color: white;

    &:hover {
      background: #3182ce;
      transform: translateY(-1px);
    }
  }

  &.btn-secondary {
    background: #718096;
    color: white;

    &:hover {
      background: #4a5568;
      transform: translateY(-1px);
    }
  }

  &.btn-info {
    background: #38b2ac;
    color: white;

    &:hover {
      background: #319795;
      transform: translateY(-1px);
    }
  }

  &.btn-success {
    background: #48bb78;
    color: white;

    &:hover {
      background: #38a169;
      transform: translateY(-1px);
    }
  }

  &.btn-warning {
    background: #ed8936;
    color: white;

    &:hover {
      background: #dd6b20;
      transform: translateY(-1px);
    }
  }

  &.btn-danger {
    background: #f56565;
    color: white;

    &:hover {
      background: #e53e3e;
      transform: translateY(-1px);
    }
  }

  &.btn-purple {
    background: #9f7aea;
    color: white;

    &:hover {
      background: #805ad5;
      transform: translateY(-1px);
    }
  }

  &.btn-gray {
    background: #a0aec0;
    color: white;

    &:hover {
      background: #718096;
      transform: translateY(-1px);
    }
  }
}
.type-selector,
.level-selector {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
  font-size: 14px;
  background: white;
  cursor: pointer;
  transition: all 0.2s ease;

  &:focus {
    outline: none;
    border-color: #4299e1;
    box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.1);
  }

  &:hover {
    border-color: #9ca3af;
  }

  option {
    padding: 4px;
  }
}
.test-mind {
  flex: 1;
}
</style>
